# -*- coding:utf-8 -*-
# @Time : 2021-12-28 10:23 
# @Author : suny570
# @Site   : 
# @File : semantic_search.py 
# @Software: PyCharm

import os
from src.intelligent_interaction.engine.model_inference import BasePredictor
faq = BasePredictor('encyclopedia')

class SemanticSearch(object):

    def __init__(self, server_handle, model=None):
        self.server_handle = server_handle
        # self.index_name = index_name
        # self.type_name = type_name
        #self.query_json = query_json
        self.model = model

    # 调用标准的库， 供测试
    def standard_search_inter(self, index_name, type_name, query_json, hit_times=None):
        """
        标准答案搜索
        :param index_name:
        :param type_name:
        :param query_json:
        :param hit_times:
        :return:
        """
        query_content = query_json['query']
        ###  FAQ result
        faq_results = faq.predict(query_content)
        faq_answers = [res[0] for res in faq_results]      # answer 答案
        faq_confidences = [res[1] for res in faq_results]  # answer 置信度

        # print("FAQ:", faq_results)
        jsons = self.server_handle.search_used_field_match_item(index_name, type_name, "question", query_content, hit_times) # 问题找答案
        faq_jsons = []  # faq 的结果集合
        for ans in list({}.fromkeys(faq_answers).keys()):
            faq_jsons.extend(self.server_handle.search_used_field_match_item(index_name, type_name, "answer", ans, 1)) # 答案找问题
        
        if len(faq_jsons) != 0:
            faq_jsons.extend(jsons)  # 拓展faq结果
        else:
            faq_jsons = jsons

        ret_document = []   # 返回的答案结果数组
        ret_profix = 'rank_number_'
        record_num = 1      # 返回答案的序号
        ### 检索字段并保存字段值（解析json集合）
        for hits in faq_jsons:
            item_map = {}
            item_map['data_id'] = hits["id"]
            item_map['user_id'] = hits["user_id"]
            item_map['title'] = hits["title"]
            item_map['content_type'] = hits["content_type"]
            item_map['content'] = hits["answer"]
            item_map['standard_question'] = hits["question"]
            item_map['content_link'] = ''
            item_map['content_ana_type'] = ''
            item_map['status'] = hits['status']
            item_map['create_time'] = hits['create_time']
            item_map['update_time'] = hits["update_time"]
            item_map['rank_num'] = ret_profix+str(record_num)
            ret_document.append(item_map)
            #ret_document[ret_profix+str(record_num)] = item_map
            record_num += 1
        self.hottop_search_inter(ret_document)
        # print("Result:", ret_document)
        return ret_document


    def standard_search_inter_strategy(self, index_name, type_name, query_json, hit_times=None):
        """
        问题搜索策略
        1. 语义解析接口，取top1
        2. 检索策略，
                     用户制定检索库，运用1的结果去检索，
                     否认则：
                        直接调用标准库，
                        若不成功则进入用户检索库，
                        最后兜底新文库，
        :param index_name:
        :param type_name:
        :param query_json:
        :param hit_times:
        :return:
        """
        pass

    def hottop_search_inter(self, history_data):
        """
        热点搜索策略, 根据历史搜索记录来存储hot_top文件
        :return:
        """
        ### Plan A简单策略：队列策略，进一个出一个，排在最前头
        _id, question = history_data[0]['data_id'], history_data[0]['standard_question']
        insert_hot = "{}|{}\n".format(str(_id), question)
        with open(os.getcwd() + '/src/test.txt', 'r', encoding='utf-8') as f:
            hot_list = f.readlines()

        if question not in [i.strip().split('|')[1] for i in hot_list]:
            hot_list.insert(0, insert_hot)
            with open(os.getcwd() + '/src/test.txt', 'w', encoding='utf-8') as fw:
                for l in hot_list[:10]:
                    fw.write(l)
